<template>
  <PageWrapper>
    <view class="p-32rpx">
      <wd-form ref="form" class="flex flex-col gap-32rpx" :model="model">
        <wd-cell-group border>
          <wd-input
            v-model="model.oldPassword"
            label="旧密码"
            label-width="100px"
            prop="oldPassword"
            show-password
            clearable
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <wd-input
            v-model="model.newPassword"
            label="新密码"
            label-width="100px"
            prop="newPassword"
            show-password
            clearable
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码', validator: newPassValidator }]"
          />
          <wd-input
            v-model="model.confirmPassword"
            label="确认密码"
            label-width="100px"
            prop="confirmPassword"
            show-password
            clearable
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码', validator: confirmPassValidator }]"
          />
        </wd-cell-group>
        <view class="footer">
          <wd-button type="primary" size="large" block @click="handleSubmit">提交</wd-button>
        </view>
      </wd-form>
    </view>
  </PageWrapper>
</template>
<script setup lang="ts">
  import PageWrapper from '@/components/Page/PageWrapper.vue';
  import { reactive, ref } from 'vue';
  import type { FormInstance } from 'wot-design-uni/components/wd-form/types';
  import { userUpdatePassword } from '@/api/system/profile';
  import { useUserStore } from '@/store/modules/user';

  const model = reactive<{
    oldPassword: string;
    newPassword: string;
    confirmPassword: string;
  }>({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
  });

  function newPassValidator(value: string) {
    if (value === model.oldPassword) {
      return Promise.reject('新密码不能与旧密码相同');
    }
    return Promise.resolve();
  }

  function confirmPassValidator(value: string) {
    if (value !== model.newPassword) {
      return Promise.reject('确认密码与新密码不一致');
    }
    return Promise.resolve();
  }

  const form = ref<FormInstance>();

  const userStore = useUserStore();
  async function handleSubmit() {
    if (!form.value) return;
    try {
      const { valid } = await form.value.validate();
      if (!valid) return;

      uni.showModal({
        title: '提示',
        content: '确认修改密码吗?',
        success: async (res) => {
          if (res.confirm) {
            await userUpdatePassword(model);
            await userStore.logout();
          }
        },
      });
    } catch (e) {
      console.warn(e);
    }
  }
</script>

<style scoped></style>
